package com.hoshiicloud.vericenter.util;

import java.util.Base64;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * @program: hoshiibuy
 * @description: 正则校验工具类
 * @author: Mr.wu
 * @create: 2019-06-24 17:49
 **/
public class RegexUtil {
    /**
     * @param str
     * @return boolean
     * @author: Mr.wu
     * @descripton: 判断字符串是否为url
     * @date: 18:36 2019/6/24
     */
    public static boolean isUrl(String str){
        String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$";
        Pattern pattern = Pattern.compile(regex);
        if (pattern.matcher(str).matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param str
     * @return boolean
     * @author: Mr.wu
     * @descripton: 判断字符串是否为base64字符串
     * @date: 18:36 2019/6/24
     */
    public static boolean isBase64Str(String str){
        String inputStr=str;
        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        if (inputStr.lastIndexOf(",") != -1) {
            inputStr= inputStr.substring(inputStr.lastIndexOf(",") + 1);
        }
        Boolean isLegal = inputStr.matches(base64Pattern);
        if (isLegal) {
           return true;
        }
        else{
            return false;
        }
    }

    /**
     * @param str
     * @return boolean
     * @author: Mr.wu
     * @descripton: 判读字符串是否为base64图片字符串
     * @date: 18:36 2019/6/24
     */
    public static boolean isBase64Img(String str){
        try {
            // BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(str)));
            BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(str)));
            if (null == bufImg) {
                System.out.println("输入的不是Base64编码的图片。");
            }
            else{
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
